package autoload

import (
	"fmt"
	"os"
	"regexp"
	"strings"

	"gitee.com/csingo/csingo/global"
)

func Execute() {
	var commandArgument string
	var paramArgs []string
	var reg = regexp.MustCompile(`^[\w_]+::[\w_]+$`)

	argsCount := len(os.Args)
	if argsCount <= 1 {
		commandArgument = "help::doc"
	} else if argsCount >= 2 {
		if !reg.Match([]byte(os.Args[1])) {
			switch os.Args[1] {
			default:
				commandArgument = "help::doc"
				if len(os.Args) == 3 {
					paramArgs = []string{fmt.Sprintf("--name=%s", os.Args[2])}
				}
			case "version":
				commandArgument = "version::show"
			case "update":
				commandArgument = "version::update"
			}
		} else {
			commandArgument = os.Args[1]
			paramArgs = os.Args[2:]
		}
	}

	var cmd, method string
	var params = make(map[string]string)
	var argReg = regexp.MustCompile(`^--[\w_]+=`)

	commandArgs := strings.Split(commandArgument, "::")
	cmd = commandArgs[0]
	method = commandArgs[1]

	for _, arg := range paramArgs {
		if !argReg.Match([]byte(arg)) {
			continue
		}
		tempParams := strings.Split(arg, "=")
		key := strings.TrimPrefix(tempParams[0], "--")
		val := tempParams[1]
		params[key] = val
	}

	global.Container.Run(cmd, method, params)
	fmt.Println()
}
